package com.stu.day17;

/**
 * @author zy
 * @date 2025/2/18 09:40
 */
public class SynchronizedDemo {
    public void method1(){
        System.out.println(Thread.currentThread().getName() + ": begin method1");

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println(Thread.currentThread().getName() + ": end method1");
    }

    public static void method2(){
        synchronized (SynchronizedDemo.class){
            System.out.println(Thread.currentThread().getName() + ": begin method2");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println(Thread.currentThread().getName() + ": end method2");
        }
    }
}
class SynchronizedTest{
    public static void main(String[] args) {
        SynchronizedDemo sd = new SynchronizedDemo();
        // t1,t2用同一个对象,要上锁
        Thread t1 = new Thread(()->sd.method1(), "t1");
        Thread t2 = new Thread(()->sd.method1(), "t2");
        t1.start();
        t2.start();

        Thread t3 = new Thread(()->SynchronizedDemo.method2(), "t3");
        Thread t4 = new Thread(()->SynchronizedDemo.method2(), "t4");
        t3.start();
        t4.start();
    }
}

